<?php
namespace app\index\command;

use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\console\input\Option;
use think\Request;
use Carbon\Carbon;
use think\Log;
use \think\Exception;

/**
 * 维护命令
 */
class Maintain extends Command
{
    public $op = [
        'setShareToRentCalendar' => 'setShareToRentCalendar',
        'setWishStatus'          => 'setWishStatus',
        'setOrderStatus'         => 'setOrderStatus',
        'cancelOutWishs'         => 'cancelOutWishs',
        'clearQueue'             => 'clearQueue',
        'refreshResources'       => 'refreshResources'
    ];

    protected function configure()
    {
        $this->setName('w')->addOption('OP', 'o', Option::VALUE_REQUIRED)->setDescription('Maintain');
    }

    protected function execute(Input $input, Output $output)
    {
        $o = $this->op[$input->getOption('OP')];
        $output->writeln($this->{$o}());
    }
    /**
     * 符合房车分享状态转出租分享状态
     */
    protected function setShareToRentCalendar()
    {
        try {
            $calendar_model = model('user/Calendar');
            $start_date     = Carbon::now()->toDateString();
            $end_date       = Carbon::now()->addDay(2)->toDateString();
            $where = [
                'start_date' => $start_date, 
                'end_date' => $end_date, 
                'shares' => 1, 
                'rents' => 0, 
                'wishs' => 0, 
                'orders' => 0
            ];
            $cars = $calendar_model->setWhere($where)->distinct(true)->field('caravan_id')->select();

            foreach ($cars as $car) {
                $calendar_model->changeUserCaravanCarlendarIsrent($car->caravan_id, $start_date, $end_date);
            }
            return 'setShareToRentCalendar Successed';
        } catch (\Exception $e) {
            return 'setShareToRentCalendar Fail';
        }
    }
    /**
     * [refreshResources 刷新时间段]
     * @return [type] [description]
     */
    protected function refreshResources()
    {
        $calendar_model = model('user/CarCalendar');
        $car_model      = model('user/Calendar');
        $caravaninfo    = model('user/CaravanInfos');
        $now_time       = date('Y-m-d');
        //出租
        $rent_cars      = $calendar_model->field('caravan_id')->where(['s'=>['<',$now_time]])->where(['sign' => 2])->select();
        if (!empty($rent_cars)) {
            foreach ($rent_cars as $car) {
                $calendar_model->where('caravan_id', $car->caravan_id)->delete();
                $caravans_info = $caravaninfo->where('id',$car->caravan_id)->find();
                $car_model->setRentDateLine($car->caravan_id,$caravans_info);
            }
        }
        //分享
        $share_cars      = $calendar_model->field('caravan_id')->where(['s'=>['<',$now_time]])->where(['sign' => 1])->select();
        if (!empty($share_cars)) {
            foreach ($share_cars as $car) {
                $calendar_model->where('caravan_id', $car->caravan_id)->delete();
                $caravans_info = $caravaninfo->where('id',$car->caravan_id)->find();
                $car_model->setShareDateline($car->caravan_id,$caravans_info);
            }
        } 
        return 'refreshResources Successed';
    }

    /**
     * 恢复超时心愿的房车状态
     */
    protected function setWishStatus()
    {
        $wishs_model       = model('user/Wishs');
        $wishs_users_model = model('user/WishUsers');
        $c                 = Carbon::now()->subHours(24)->toDateTimeString();//24小时前
        $now               = Carbon::now()->toDateTimeString();

        if ($wishs_lists = $wishs_users_model->where(['status' => 0, 'created_at' => ['<=', $c]])->select()) {
            foreach ($wishs_lists as $wishs_list) {
                $wishs_model->cancelMeetTheDemand($wishs_list->wish_id, $wishs_list->meet_user_id);
            }
        }
        return 'setWishStatus Successed';
    }
    
     /**
     * 取消过期心愿
     */
    protected function cancelOutWishs()
    {
        $wishs_model       = model('user/Wishs');
        $now               = Carbon::now()->toDateTimeString();
        if ($wishs_lists = $wishs_model->where(['status' => 0, 'start_date' => ['<=', $now]])->select()) {
            foreach ($wishs_lists as $wishs_list) {
                $wishs_model->cancelWish([$wishs_list->id],true);
            }
        }
        return 'cancelOutWishs Successed';
    }
    
    /**
     * 设置超时订单状态
     */
    protected function setOrderStatus()
    {
        $order_model = model('user/Orders');
        $c           = Carbon::now()->subMinutes(60)->toDateTimeString();//一个小时前

        $order_model->startTrans();
        try {
            $orders = $order_model->where(['status' => ['=', 100], 'created_at' => ['<', $c]])->select();
            foreach ($orders as $order) {
                if ($orders->status == 104) {
                    $userinfo = model('user/Users')->where('id',$order->rent_user_id)->find();
                    $userinfo->integral = $userinfo->integral + $order->total_intergral;
                    $userinfo->save();//订单超时返还旅行币
                }
                $order->status = 103;
                $order->save();
                $time = model('user/Calendar')->delordered($order->caravan_id, $order->rent_user_id, $order->take_car_date, $order->leave_car_date);//同步日历
            }
            $order_model->commit();
                        
        } catch (\Exception $e) {
            $order_model->rollback();
            return 'setOrderStatus Failed';
        }
        return 'setOrderStatus Successed';
    }
    /**
     * 取消过时队列任务
     */
    protected function clearQueue()
    {
        try {
            db('jobs')->where('created_at', '<', Carbon::now()->subMinutes(60)->timestamp)->delete();
            return 'setOrderStatus Successed';
        } catch (\Exception $e) {
            
        }
    }
    /**
     * 分享未成功赠送旅行币
     */
    // public function giveShareIntergrate()
    // {
    //     $caravan_calendar = model('user/CarCalendar');
    //     $today     = Carbon::now()->toDateString();
    //     $yestoday     = Carbon::now()->addDay(-1)->toDateString();
    //     $object = $caravan_calendar->where('e',$yestoday)->column('s');
    // }
}